package parser

import (
	"strings"

	"gitee.com/zfd81/dbrs/sql"
	"gitee.com/zfd81/dbrs/sql/nodes"

	"vitess.io/vitess/go/vt/sqlparser"
)

func convertShow(s *sqlparser.Show, query string) (Statement, error) {
	var stmt *ShowStatement
	switch show := s.Internal.(type) {
	case *sqlparser.ShowBasic:
		cmd := strings.TrimSpace(show.Command.ToString())
		switch cmd {
		case sqlparser.KeywordString(sqlparser.DATABASES):
			stmt = NewShowStatement(query, nodes.NewShowDatabases())
		case sqlparser.KeywordString(sqlparser.TABLES):
			stmt = NewShowStatement(query, nodes.NewShowTables(show.Full))
		case sqlparser.KeywordString(sqlparser.STATUS):
			stmt = NewShowStatement(query, nodes.NewShowStatus())
		case sqlparser.KeywordString(sqlparser.CHARSET):
			stmt = NewShowStatement(query, nodes.NewShowCharset())
		case sqlparser.KeywordString(sqlparser.COLLATION):
			stmt = NewShowStatement(query, nodes.NewShowCollation())
		case sqlparser.KeywordString(sqlparser.VARIABLES):
			stmt = NewShowStatement(query, nodes.NewShowVariables())
		default:
			//return nil, fmt.Errorf("unsupported syntax: %#v", cmd)
			stmt = NewShowStatement(query, nil)
		}
		stmt.Command = cmd
		stmt.Full = show.Full
		stmt.Tbl = strings.TrimSpace(show.Tbl.Name.String())
		stmt.Db = strings.TrimSpace(show.DbName.String())
		if show.Filter != nil {
			stmt.Filter = show.Filter.Like
		}
	default:
		stmt = NewShowStatement(query, nil)
	}

	return stmt, nil
}

type ShowStatement struct {
	BaseStatement
	Command string
	Full    bool
	Tbl     string
	Db      string
	Filter  string
}

func NewShowStatement(query string, node sql.Node) *ShowStatement {
	stmt := &ShowStatement{}
	stmt.sql = query
	stmt.node = node
	return stmt
}
